package com.example.homework08;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.content.SharedPreferences;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SharedPreference extends Fragment {
    private String FILE_NAME = "sharePreference.txt";
    private EditText nameEditText;
    private EditText numEditText;


    public SharedPreference() {
        super(R.layout.sharedpreference);
    }

    @Override
    public void onViewCreated(@NonNull View view, @NonNull Bundle saveInstanceState) {
        super.onViewCreated(view, saveInstanceState);

        nameEditText = getView().findViewById(R.id.nameEditText);
        numEditText = getView().findViewById(R.id.ageEditText);


        //写入数据
        SharedPreferences settings = getActivity().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        getView().findViewById(R.id.save_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("Number", nameEditText.getText().toString());
                editor.putString("password", numEditText.getText().toString());

                try {
                    MessageDigest md = MessageDigest.getInstance("SHA-256");    // 将此换成SHA-1、SHA-512、SHA-384等参数
                    md.update(numEditText.getText().toString().getBytes(Charset.forName("UTF-8")));
                    editor.putString("password", String.valueOf(md.digest()));
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                editor.apply();
                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
            }
        });

        //读取数据
        nameEditText.setText(settings.getString("Number", ""));
        numEditText.setText(settings.getString("password", ""));

    }
}

